/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BuyPointCardActivity.java
 *   @Date: 18-11-30 下午7:45
 *   @Author: ppzhao
 *   @Description:购买点卡
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.point.ui;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.point.presenter.BuyPointCardPresenter;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.ClickProxy;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.Urls;
import io.bhex.sdk.point.bean.PointCardBalanceListResponse;
import io.bhex.sdk.point.bean.PointCardPackageDetail;

public class BuyPointCardActivity extends BaseActivity<BuyPointCardPresenter,BuyPointCardPresenter.BuyPointCardUI> implements BuyPointCardPresenter.BuyPointCardUI, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private String perPointNum;
    private ArrayList<TextView> payWayViews;
    private String defaultPayToken="";
    private EditText editBuyNum;
    private String payToken="";
    private TopBar topBar;
    private String payMoney="";
    private String currentTokenFree="";
    //点卡可售额度
    private String normal="";
    private CheckBox protocalBx;
    private Button payBtn;
    private String valueBaseTokenId="";
    private String valueBaseTokenRate="";
    private List<PointCardPackageDetail.DiscountPriceListBean> discountPriceList;
    //是否限制点卡购买额度 默认不限制
    private boolean isLimitBuyPoints=false;

    @Override
    protected int getContentView() {
        return R.layout.activity_buy_point_card_layout;
    }

    @Override
    protected BuyPointCardPresenter createPresenter() {
        return new BuyPointCardPresenter();
    }

    @Override
    protected BuyPointCardPresenter.BuyPointCardUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();

        payWayViews = new ArrayList<TextView>();
        payWayViews.add(viewFinder.textView(R.id.p_select_pay_way_a));
        payWayViews.add(viewFinder.textView(R.id.p_select_pay_way_b));
        payWayViews.add(viewFinder.textView(R.id.p_select_pay_way_c));
        editBuyNum = viewFinder.editText(R.id.p_buy_num_edit);
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.goPointCardRule(BuyPointCardActivity.this);
            }
        });
        protocalBx = viewFinder.find(R.id.protocol_checkbox);
        payBtn = viewFinder.find(R.id.p_pay_btn);

    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.textView(R.id.p_select_pay_way_a).setOnClickListener(this);
        viewFinder.textView(R.id.p_select_pay_way_b).setOnClickListener(this);
        viewFinder.textView(R.id.p_select_pay_way_c).setOnClickListener(this);
        viewFinder.textView(R.id.p_buy_sub).setOnClickListener(this);
        viewFinder.textView(R.id.p_buy_add).setOnClickListener(this);
        viewFinder.textView(R.id.p_pay_btn).setOnClickListener(this);
        viewFinder.find(R.id.protocol_linea).setOnClickListener(this);
        viewFinder.find(R.id.pointcard_protocol).setOnClickListener(this);
        protocalBx.setOnCheckedChangeListener(this);
        editBuyNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String num = editBuyNum.getText().toString();
                if (TextUtils.isEmpty(num)){
//                    editBuyNum.setText("1");
                    updatePointNum();
                    return;
                }
                if (Integer.valueOf(num)<1){
                    editBuyNum.setText("1");
                }
                if (Integer.valueOf(num)>10000){
                    editBuyNum.setText("10000");
                }
                updatePointNum();

                editBuyNum.setSelection(editBuyNum.getText().toString().length());
            }
        });

        viewFinder.find(R.id.p_pay_btn).setOnClickListener(new ClickProxy(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                //点卡购买
                goBuy();
            }
        }));
    }

    /**
     * 购买点卡
     */
    private void goBuy() {
        //要买入的点卡份数
        String numStr = editBuyNum.getText().toString();
        if (TextUtils.isEmpty(numStr)) {
            ToastUtils.showLong(this, getString(R.string.string_hint_input_point_card));
            return;
        }

        if (!protocalBx.isChecked()) {
            ToastUtils.showShort(this,getResources().getString(R.string.hint_must_agree_pointcard_protocol));
            return;
        }

        if (TextUtils.isEmpty(payToken)) {
            ToastUtils.showLong(this, getString(R.string.string_insufficient_balance));
            return;
        }
//        //可买的点卡份数
//        double nums = NumberUtils.div(perPointNum, normal);
//        double diffBuy = NumberUtils.sub(numStr,nums+"");
//        if (isLimitBuyPoints&&diffBuy>0){
//            ToastUtils.showLong(getString(R.string.string_insufficient_balance));
//            return;
//        }

        double diff = NumberUtils.sub(currentTokenFree, payMoney);
        if (diff<0||TextUtils.isEmpty(currentTokenFree)){
            ToastUtils.showLong(this, getString(R.string.string_insufficient_balance));
            return;
        }
        getPresenter().buyPointCard(numStr,payToken);
    }


    private void updatePointNum() {
        //购买点卡份数
        String numStr = editBuyNum.getText().toString();
        updateHandFee(numStr);
        double numD = NumberUtils.mul(numStr, perPointNum);
        String num = NumberUtils.roundFormatDown(numD, 0);
        viewFinder.textView(R.id.p_buy_num_pts).setText(getString(R.string.string_format_buy_num_pts,num));
        if (discountPriceList != null) {
            for (PointCardPackageDetail.DiscountPriceListBean discountPriceListBean : discountPriceList) {
                String tokenId = discountPriceListBean.getTokenId();
                String price = discountPriceListBean.getPrice();
                if (payToken.equals(tokenId)){
                    double payAmountD = NumberUtils.mul(numStr, price);
                    String payAmount = NumberUtils.roundFormatDown(payAmountD, AppData.Config.DIGIT_DEFAULT_VALUE);
                    payMoney = payAmount;
                    viewFinder.textView(R.id.p_pay).setText(getString(R.string.string_format_need_pay,payAmount,payToken));
                    if ("USDT".equals(payToken)&&!TextUtils.isEmpty(price)) {
//                    if (valueBaseTokenId.equals(payToken)&&!TextUtils.isEmpty(price)) {
                        viewFinder.textView(R.id.p_pay_about).setVisibility(View.INVISIBLE);
                    }else{
                        viewFinder.textView(R.id.p_pay_about).setVisibility(View.VISIBLE);
                    }
                }

                if ("USDT".equals(tokenId)&&!TextUtils.isEmpty(price)){
//                if (valueBaseTokenId.equals(tokenId)&&!TextUtils.isEmpty(price)){
                    double payAmountD2 = NumberUtils.mul(numStr, price);
                    String payAmount2 = NumberUtils.roundFormatDown(payAmountD2, AppData.Config.DIGIT_DEFAULT_VALUE);
                    viewFinder.textView(R.id.p_pay_about).setText(getString(R.string.string_format_about_pay,payAmount2,"USDT"));
                }

            }
        }
    }

    @Override
    public void showPointDetail(PointCardPackageDetail response) {
        if (response != null) {
            String pointCardId = response.getPointCardId();

            if (pointCardId.equals("BHEX_UCARD")) {
                //USDT点卡
                updateCardStyle(true);
            }else{
                updateCardStyle(false);
            }
            topBar.setTitle(response.getName());
            viewFinder.textView(R.id.p_name).setText(response.getName());
            //套餐点卡数量
            perPointNum = NumberUtils.subZeroAndDot(response.getPointQuantity());
            viewFinder.textView(R.id.p_buy_num_pts).setText(getString(R.string.string_format_buy_num_pts,perPointNum));
            PointCardPackageDetail.DescMapBean descMap = response.getDescMap();
            if (descMap != null) {
                viewFinder.textView(R.id.p_buy_max_title).setText(descMap.getAvailable());
                viewFinder.textView(R.id.p_value_trade_title).setText(descMap.getFee_word());
                if (!TextUtils.isEmpty(descMap.getBonus())) {
                    viewFinder.textView(R.id.p_gift_content).setText(descMap.getBonus());
                    viewFinder.textView(R.id.p_gift_content).setVisibility(View.VISIBLE);
                }else{
                    viewFinder.textView(R.id.p_gift_content).setVisibility(View.GONE);
                }
            }
            PointCardPackageDetail.PointCardBean pointCard = response.getPointCard();
            if (pointCard != null) {
                //锚定币种
                valueBaseTokenId = pointCard.getValueBaseTokenId();
                //等值交易手续费
                viewFinder.textView(R.id.p_value_trade).setText(pointCard.getBaseExchangeRateDesc());
                //锚定基准比例 1点卡=xxx token
                valueBaseTokenRate = pointCard.getValueBaseTokenRate();
                //默认一份
                updateHandFee("1");
            }

            discountPriceList = response.getDiscountPriceList();
            if (discountPriceList != null) {
                for (PointCardPackageDetail.DiscountPriceListBean discountPriceListBean : discountPriceList) {
                    String tokenId = discountPriceListBean.getTokenId();
                    String price = discountPriceListBean.getPrice();
                    int defaultPay = discountPriceListBean.getDefaultPay();
                    if (defaultPay==1) {
                        defaultPayToken = tokenId;
                        payToken = defaultPayToken;
                        getPresenter().getAsset(payToken);
                    }

                    if (valueBaseTokenId.equals(tokenId)) {
                        //单价
//                        double unitPriceD = NumberUtils.mul(price, perPointNum);
                        String unitPrice = NumberUtils.subZeroAndDot(price);
                        viewFinder.textView(R.id.p_unit_price).setText(getString(R.string.string_format_unit_price,response.getPointQuantity(),unitPrice,valueBaseTokenId));
                    }
                }

                if (discountPriceList!=null&&discountPriceList.size()>0) {
                    for (int i = 0; i < payWayViews.size(); i++) {
                        TextView textView = payWayViews.get(i);
                        if (discountPriceList.size()>i){
                            textView.setText(discountPriceList.get(i).getTokenId());
                            textView.setVisibility(View.VISIBLE);
                            if (defaultPayToken.equals(discountPriceList.get(i).getTokenId())) {
                                textView.setBackgroundResource(R.drawable.bg_rect_blue);
                                updatePayWay(textView.getId());
                            }else{
                                textView.setBackgroundResource(R.drawable.bg_rect_gray);
                            }
                        }else{
                            textView.setVisibility(View.GONE);
                        }
                    }
                }
            }

            editBuyNum.setText("1");


        }
    }

    /**
     * 更新卡片样式
     * @param isBlack
     */
    private void updateCardStyle(boolean isBlack) {
        if (isBlack) {
            viewFinder.find(R.id.p_card_view).setBackgroundResource(R.mipmap.pointcard_bg_black);
            viewFinder.textView(R.id.p_name).setTextColor(Color.parseColor("#E6FFFFFF"));
            viewFinder.textView(R.id.p_buy_max_title).setTextColor(Color.parseColor("#99FFFFFF"));
            viewFinder.textView(R.id.p_value_trade_title).setTextColor(Color.parseColor("#99FFFFFF"));
            viewFinder.textView(R.id.p_buy_max).setTextColor(Color.parseColor("#FFFFFF"));
            viewFinder.textView(R.id.p_value_trade).setTextColor(Color.parseColor("#FFFFFF"));
            viewFinder.textView(R.id.p_gift_content).setTextColor(Color.parseColor("#CCEBD1AD"));
            viewFinder.textView(R.id.p_gift_content).setBackgroundResource(R.drawable.bg_circle_pointcard_black);
            viewFinder.textView(R.id.p_gift_content).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.icon_gift_black),null,null,null);
        }else{
            viewFinder.find(R.id.p_card_view).setBackgroundResource(R.mipmap.pointcard_bg_yellow);
            viewFinder.textView(R.id.p_name).setTextColor(Color.parseColor("#E6735D4E"));
            viewFinder.textView(R.id.p_buy_max_title).setTextColor(Color.parseColor("#B3735D4E"));
            viewFinder.textView(R.id.p_value_trade_title).setTextColor(Color.parseColor("#B3735D4E"));
            viewFinder.textView(R.id.p_buy_max).setTextColor(Color.parseColor("#735D4E"));
            viewFinder.textView(R.id.p_value_trade).setTextColor(Color.parseColor("#735D4E"));
            viewFinder.textView(R.id.p_gift_content).setTextColor(Color.parseColor("#CC735D4E"));
            viewFinder.textView(R.id.p_gift_content).setBackgroundResource(R.drawable.bg_circle_pointcard_yellow);
            viewFinder.textView(R.id.p_gift_content).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.icon_gift_yellow),null,null,null);
        }
    }

    /**
     * 更新抵扣手续费
     * @param num 购买份数
     */
    private void updateHandFee(String num) {

        double pointNumD = NumberUtils.mul(num, perPointNum);
        String pointNum = String.valueOf(pointNumD);
        String feeValue = NumberUtils.mul(valueBaseTokenRate,pointNum)+"";
        feeValue = NumberUtils.subZeroAndDot(feeValue);
//        viewFinder.textView(R.id.p_value_fee).setText(getString(R.string.string_format_buy_num_pts,perPointNum)+feeValue+" "+valueBaseTokenId);
        viewFinder.textView(R.id.p_value_fee).setText(feeValue+" "+valueBaseTokenId);

    }

    @Override
    public void showPointBalance(PointCardBalanceListResponse response) {
        normal = response.getPointLimit();
        normal = NumberUtils.roundFormatDown(normal,0);
        viewFinder.textView(R.id.p_buy_max).setText(normal);
        if (normal.equals("-1")) {
            //接口协定=-1时，不限额
            viewFinder.textView(R.id.p_buy_max_title).setVisibility(View.GONE);
            viewFinder.textView(R.id.p_buy_max).setVisibility(View.GONE);
            isLimitBuyPoints = false;
        }else{
            viewFinder.textView(R.id.p_buy_max_title).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.p_buy_max).setVisibility(View.VISIBLE);
            isLimitBuyPoints = true;
        }

    }

    @Override
    public void updateAssettByToken(String token, String free) {
        if (token.equals(payToken)) {
            currentTokenFree = free;
            free = NumberUtils.roundFormatDown(free,AppData.Config.DIGIT_DEFAULT_VALUE);
            viewFinder.textView(R.id.p_balance_available).setText(getString(R.string.string_format_available_balance,free,token));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.p_select_pay_way_a:
                updatePayWay(R.id.p_select_pay_way_a);
                break;
            case R.id.p_select_pay_way_b:
                updatePayWay(R.id.p_select_pay_way_b);
                break;
            case R.id.p_select_pay_way_c:
                updatePayWay(R.id.p_select_pay_way_c);
                break;
            case R.id.p_buy_sub:
                buyNumAddSub(false);
                break;
            case R.id.protocol_linea:
                protocalBx.setChecked(!protocalBx.isChecked());
                break;
            case R.id.pointcard_protocol:
                WebActivity.runActivity(this,getString(R.string.string_pointcard_protocol),Urls.H5_URL_POINTCARD_SERVICE);
                break;
            case R.id.p_buy_add:
                buyNumAddSub(true);
                break;
        }
    }

    private void buyNumAddSub(boolean isAdd) {
        String numStr = editBuyNum.getText().toString();
        if (!TextUtils.isEmpty(numStr)){
            int num =1;
            if (isAdd) {
                num = Integer.valueOf(numStr)+1;
            }else{
                num = Integer.valueOf(numStr)-1;
            }
            if (num<1){
                num=1;
            }
            editBuyNum.setText(""+num);
        }else{
            editBuyNum.setText("1");
        }
    }

    /**
     * 更新支付方式
     * @param selectId
     */
    private void updatePayWay(int selectId) {
        viewFinder.textView(R.id.p_balance_available).setText(getString(R.string.string_format_available_balance,"0.00000000",""));
        currentTokenFree ="";
        payMoney="";
        for (TextView payWayView : payWayViews) {
            if (payWayView.getId()==selectId) {
                payWayView.setBackgroundResource(R.drawable.bg_rect_blue);
                payToken = payWayView.getText().toString();
                viewFinder.textView(R.id.p_balance_available).setText(getString(R.string.string_format_available_balance,"0.00000000",payToken));
                getPresenter().getAsset(payToken);
                if (discountPriceList != null) {
                    for (PointCardPackageDetail.DiscountPriceListBean discountPriceListBean : discountPriceList) {
                        String tokenId = discountPriceListBean.getTokenId();
                        if (payToken.equals(tokenId)) {
                            String priceUnit = discountPriceListBean.getPrice();
//                            priceUnit = NumberUtils.roundFormatDown(priceUnit,2);
                            priceUnit = NumberUtils.subZeroAndDot(priceUnit);
                            viewFinder.textView(R.id.p_unit_price).setText(getString(R.string.string_format_unit_price,perPointNum,priceUnit,payToken));
                        }
                    }
                }

            }else{
                payWayView.setBackgroundResource(R.drawable.bg_rect_gray);
            }

        }

        updatePointNum();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        payBtn.setEnabled(isChecked);
    }
}
